package model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.Semaphore;

import controller.Controller;

public class HumanPlayer extends Player {
	
	private Controller controller;
	private Semaphore semaphore = null;
	private int cardIndex = 0;

	public HumanPlayer(int playerID, String humanPlayerName, Semaphore semaphore, Controller controller) {
		super(playerID,humanPlayerName);
		this.semaphore = semaphore;
		this.controller = controller;
	}

	public Card askForACard(ArrayList<Card> calledCards,
			int thPlayer, Colors trumpColor) {
		
		try {
			controller.enableUserInteraction();
			this.semaphore.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		controller.disableUserInteraction();
		
		return cards.get(cardIndex);
	}

	public int askForABid(int playersNumber, Colors trumpColor) {
		int temp = 0;
		try {
			temp = controller.askABidFromTheUser();
			semaphore.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return temp;
	}
	
	public void sortCards(Colors trumpColor) {
		ArrayList<Card> trumpCards = new ArrayList<Card>();
		ArrayList<Card> diamondCards = new ArrayList<Card>();
		ArrayList<Card> heartCards = new ArrayList<Card>();
		ArrayList<Card> spadeCards = new ArrayList<Card>();
		ArrayList<Card> clubCards = new ArrayList<Card>();
		
		for(int i = 0; i < cards.size(); ++i) {
			if (cards.get(i).getColor() == trumpColor)
				trumpCards.add(cards.get(i));
			else if (cards.get(i).getColor() == Colors.Diamond)
				diamondCards.add(cards.get(i));
			else if (cards.get(i).getColor() == Colors.Heart)
				heartCards.add(cards.get(i));
			else if (cards.get(i).getColor() == Colors.Spade)
				spadeCards.add(cards.get(i));
			else if (cards.get(i).getColor() == Colors.Club)
				clubCards.add(cards.get(i));
		}
		
		Collections.sort(trumpCards);
		Collections.sort(diamondCards);
		Collections.sort(heartCards);
		Collections.sort(spadeCards);
		Collections.sort(clubCards);
		
		cards = new ArrayList<Card>();
		if (trumpCards.size() > 0) cards.addAll(trumpCards);
		if (diamondCards.size() > 0) cards.addAll(diamondCards);
		if (heartCards.size() > 0) cards.addAll(heartCards);
		if (spadeCards.size() > 0) cards.addAll(spadeCards);
		if (clubCards.size() > 0) cards.addAll(clubCards);
	}

	public void setRemovableCardIndex(int i) {
		cardIndex = i;
	}
}